简书链接:每日分享android获取文件目录总大小实现清除缓存
文章字数:232,阅读全文大约需要1分钟
跟大家讲一个笑话,我维护老项目,看到有一个清除缓存功能,我看了一下怎么实现的,结果就一个Toast
太逗比了
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| /** * 获取指定文件夹的大小 * * @param f * @return * @throws Exception */ public static long getFileSizes(File f) { long size = 0; File flist[] = f.listFiles();//文件夹目录下的所有文件 if (flist == null) {//4.2的模拟器空指针。 return 0; } if (flist != null) { for (int i = 0; i < flist.length; i++) { if (flist[i].isDirectory()) {//判断是否父目录下还有子目录 size = size + getFileSizes(flist[i]); } else { size = size + getFileSize(flist[i]); } } } return size; }
|
获取文件大小
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
| }
/** * 获取指定文件的大小 * * @return * @throws Exception */ public static long getFileSize(File file) {
long size = 0; if (file.exists()) { FileInputStream fis = null; try { fis = new FileInputStream(file);//使用FileInputStream读入file的数据流 size = fis.available();//文件的大小 } catch (IOException e) { e.printStackTrace(); } finally { try { fis.close(); } catch (IOException e) { e.printStackTrace(); } }
} else { } return size; }
|
计算当前应用缓存文件夹
1 2 3 4 5
| File file1 = AppContext.getInstance().getCacheDir(); File file2 = AppContext.getInstance().getExternalCacheDir(); long fileSizes = FileUtils.getFileSizes(file1); long fileSizes2 = FileUtils.getFileSizes(file2); return fileSizes + fileSizes2;
|
清除所有缓存
1 2 3 4 5 6 7 8 9 10 11 12 13
| public static boolean clearAllCache() { File externalCacheDir = SuperAppContext.getInstance().getExternalCacheDir(); File cacheDir = SuperAppContext.getInstance().getCacheDir(); boolean result = false; if (cacheDir != null) { result = delAllFile(cacheDir.getAbsolutePath()); } if (externalCacheDir != null) {
result = delAllFile(externalCacheDir.getAbsolutePath()) || result ? true : false;//原生是真 或者现在是true就是true } return result; }
|
删除文件夹
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
| //删除指定文件夹下所有文件 //param path 文件夹完整绝对路径 public static boolean delAllFile(String path) { boolean flag = false; File file = new File(path); if (!file.exists()) { return flag; } if (!file.isDirectory()) { return flag; } String[] tempList = file.list(); File temp = null; for (int i = 0; i < tempList.length; i++) { if (path.endsWith(File.separator)) { temp = new File(path + tempList[i]); } else { temp = new File(path + File.separator + tempList[i]); } if (temp.isFile()) { temp.delete(); } if (temp.isDirectory()) { delAllFile(path + "/" + tempList[i]);//先删除文件夹里面的文件 delFolder(path + "/" + tempList[i]);//再删除空文件夹 flag = true; } } return flag; }
|
删除volley, uiversalCache文件夹
1 2 3 4 5 6 7
| public static File getVolleyCacheFile() { return productSystemCacheFolder("volley"); }
public static File getImageUniversalCacheFile() { return productSystemCacheFolder("uil-images"); }
|